package mytest;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/contact")
public class ContactListServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException {
        request.setCharacterEncoding("UTF-8");
        List<Contact> contactList = new ArrayList<>();
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/contact", "root", "root123");
            PreparedStatement ps = conn.prepareStatement("SELECT id, name, address, phone FROM contacts");
            ResultSet rs = ps.executeQuery();

            while (rs.next()) {
                // 从结果集中获取联系人数据并创建Contact对象
                Contact contact = new Contact();
                contact.setId(rs.getInt("id"));
                contact.setName(rs.getString("name"));
                contact.setAddress(rs.getString("address"));
                contact.setPhone(rs.getString("phone"));
                // 将Contact对象添加到列表中
                contactList.add(contact);
            }


            // 将联系人列表设置到request的属性中
            request.setAttribute("contacts", contactList);
            System.out.println(contactList);
            // 转发请求到显示联系人列表的JSP页面
            request.getRequestDispatcher("/contact.jsp").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

